//
//  HLNetworking.swift
//  weibo-snh
//
//  Created by 黄力 on 15/12/21.
//  Copyright © 2015年 HLTest. All rights reserved.
//

import AFNetworking

//定义请求类型的枚举
enum HLNetworkingHTTPMethod: Int {
    case GET = 0
    case POST = 1
}

class HLNetworking: AFHTTPSessionManager {
    //创建单例对象
    static let sharedNetworking: HLNetworking = {
        //创建网络管路对象
        let networking = HLNetworking(baseURL: NSURL(string: "https://api.weibo.com/"))
        //添加可解析的类型
        networking.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return networking
    }()
    
    //发送网络请求
    func sendHTTPRequest(HTTPMethod: HLNetworkingHTTPMethod, urlStr: String, parameters: [String: AnyObject], finshed: (resultData: [String: AnyObject]?, error: NSError?) -> ()) {
        
        //根据请求类型来判断请求方法
        if HTTPMethod == .GET {
            GET(urlStr, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                //判断如果返回的有数据
                if let resultdic = result as? [String: AnyObject]{
                    //成功的回调
                    finshed(resultData: resultdic, error: nil)
                }else {
                    //定义错误信息
                    let myError = NSError(domain: "com.error", code: 10000, userInfo: [NSLocalizedDescriptionKey: "您的数组出错了"])
                    print(myError)
                    //错误的回调
                    finshed(resultData: nil, error: myError)
                }
                }) { (_, error) -> Void in
                    print(error)
                    finshed(resultData: nil, error: error)
            }
            
        }else {
            POST(urlStr, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                //判断如果返回的有数据
                if let resultdic = result as? [String: AnyObject]{
                    //成功的回调
                    finshed(resultData: resultdic, error: nil)
                }else {
                    //定义错误信息
                    let myError = NSError(domain: "com.error", code: 10000, userInfo: [NSLocalizedDescriptionKey: "您的数组出错了"])
                    print(myError)
                    //错误的回调
                    finshed(resultData: nil, error: myError)
                }
                }) { (_, error) -> Void in
                    print(error)
                    finshed(resultData: nil, error: error)
            }
        }
    }
    
}
